package UDPEcho;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UDPEchoCline3 {
    private DatagramSocket socket = null;
    private String severIp;
    private int severPort;

    public UDPEchoCline3(String severIp,int severPort) throws SocketException {
        this.severIp = severIp;
        this.severPort = severPort;
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("客户端启动!!!");
        while(true){
            //等待用户从控制台输入请求
            System.out.print("->");
            if(!scanner.hasNext()){
                break;
            }
            String request = scanner.next();
            //将请求发送给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,request.getBytes().length,InetAddress.getByName(severIp),severPort);
            socket.send(requestPacket);
            //接收返回的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(responsePacket);
            //打印响应
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UDPEchoCline3 udpEchoCline3 = new UDPEchoCline3("127.0.0.1",2200);
        udpEchoCline3.start();
    }
}
